import {
  DocumentObject,
  MenuItemDefinition,
  ObjectTreeMenuProps,
  ObjectTreeMenuUtils,
  sketchUtils,
  Types,
} from '@amcax/base';
import { docMgr, commandCenters } from '@app-cad/module';
import { MessageTip } from '@app-cad/common/utils';

export const nonVisibilityTypes = [
  Types.DocRoot,
  Types.PARAMETER_OBJECT,
  Types.PARAMETER_SET,
  Types.PARAMETER_LINK,
  Types.MeasureResultRoot,
  Types.DESIGN_TABLE,
];

export const setVisibility = async (
  objects: DocumentObject[],
  visible: boolean,
) => {
  const dxidArray: string[] = [];
  for (const obj of objects) {
    if (ObjectTreeMenuUtils.initialNodeTypes.includes(obj?.type)) {
      docMgr.setLocalReferenceVisibility(obj.id, visible);
    } else if (
      obj?.dxid &&
      !nonVisibilityTypes.includes(obj.type) &&
      !(
        sketchUtils.isSketchAxesChildDxid(obj.id) ||
        sketchUtils.isSketchCurveChildId(obj.id) ||
        sketchUtils.isSketchIntersect3DChildId(obj.id) ||
        sketchUtils.isSketchConstraintChildId(obj.id)
      )
    ) {
      dxidArray.push(obj.dxid);
    }
  }

  if (dxidArray.length > 0) {
    try {
      await commandCenters.basicCommands.setVisibility(dxidArray, visible);
    } catch (error: any) {
      MessageTip.error(
        `${visible ? '显示' : '隐藏'}对象失败 - ${error.message}（Code ${error.code}）`,
      );
    }
  }
};

export const MenuItemHide: MenuItemDefinition<ObjectTreeMenuProps> = {
  id: 'hide',
  children: '隐藏',
  hidden: (props) => {
    return props.props.selectedObjects.every(
      ({ visibility, type }) =>
        !visibility || nonVisibilityTypes.includes(type),
    );
  },
  onClick: async ({ props: { selectedObjects } }) => {
    await setVisibility(selectedObjects, false);
  },
};
export const MenuItemShow: MenuItemDefinition<ObjectTreeMenuProps> = {
  id: 'show',
  children: '显示',
  hidden: (props) => {
    return props.props.selectedObjects.every(
      ({ visibility, type }) => visibility || nonVisibilityTypes.includes(type),
    );
  },
  onClick: async ({ props: { selectedObjects } }) => {
    await setVisibility(selectedObjects, true);
  },
};
